//
// Created by wei.yang on 2021/8/24.
//

#include "pcm_decoder_controller.h"

PCMDecoderController::PCMDecoderController() {
    realDecoder = NULL;
    pcmFile = NULL;
}

PCMDecoderController::~PCMDecoderController() {

}

void PCMDecoderController::init(const char *orgFilePath, const char *pcmFilePath) {
    //初始化decoder
    RealDecoder *tempDecoder = new RealDecoder();
    int metaData[2];
    tempDecoder->getMusicMeta(orgFilePath, metaData);
    delete tempDecoder;
    //初始化采样率
    sampleRate = metaData[0];
    int byteCountPreSec = sampleRate * 2 * 16 / 8;
    packetBufferSize = (int) ((byteCountPreSec / 2) * 0.2);
    realDecoder = new RealDecoder();
    realDecoder->init(orgFilePath, packetBufferSize);
    __android_log_print(ANDROID_LOG_ERROR, "RealDecoder", "init PCMDecoderController success");
    pcmFile = fopen(pcmFilePath, "wb+");
    __android_log_print(ANDROID_LOG_ERROR, "RealDecoder", "init pcmFile success");

}

void PCMDecoderController::decode() {
    __android_log_print(ANDROID_LOG_ERROR, "RealDecoder", "start decode audio data");
    while (true) {
        AudioPacket *packet = realDecoder->decodePacket();
        if (-1 == packet->size) {
            break;
        }
        __android_log_print(ANDROID_LOG_ERROR, "RealDecoder", "write buffer to file");
        fwrite(packet->buffer, sizeof(short), packet->size, pcmFile);
    }
}

void PCMDecoderController::destroy() {
    if (NULL != realDecoder) {
        realDecoder->destroy();
        delete realDecoder;
        realDecoder = NULL;
    }
    if (NULL != pcmFile) {
        fclose(pcmFile);
        pcmFile = NULL;
    }
}